package com.sp2p.task;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
//import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.allinpay.XmlTools;
import com.shove.config.AllinpayConfig;
import com.shove.web.action.AllinPaymentAction;
import com.sp2p.service.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.gofull.gateway.sms.util.SMSUtil;
import com.sp2p.dao.UserDao;
import com.sp2p.dao.InvestDao;
//import com.sp2p.constants.IFundConstants;
import com.shove.Convert;
import com.shove.base.BaseService;
import com.shove.data.DataException;
import com.shove.data.DataSet;
import com.shove.data.dao.Database;
import com.shove.data.dao.MySQL;
//import com.shove.util.BeanMapUtils;
import com.shove.util.UtilDate;
import com.shove.vo.PageBean;
import com.sp2p.constants.IConstants;
import com.sp2p.dao.AccountUsersDao;
import com.sp2p.dao.BorrowDao;
import com.sp2p.dao.FinanceDao;
import com.sp2p.dao.GofullAwardDao;
import com.sp2p.dao.FrontMyPaymentDao;
import com.sp2p.dao.FundRecordDao;
import com.sp2p.dao.RepayMentDao;
import com.sp2p.dao.admin.BorrowManageDao;
import com.sp2p.dao.admin.GroupUserDao;
import com.sp2p.database.Dao.Functions;
import com.sp2p.database.Dao.Procedures;
//import com.sp2p.service.admin.BorrowManageService;
//import com.sp2p.dao.admin.GroupUserDao;
//import com.sp2p.util.AmountUtil;
import com.sp2p.service.admin.PlatformCostService;
import com.sp2p.service.admin.SMSInterfaceService;

/**
 * @ClassName: JobTaskService.java
 * @Author: gang.lv
 * @Date: 2013-4-11 上午11:14:41
 * @Copyright: 2013 www.emis.com Inc. All rights reserved.
 * @Version: V1.0.1
 * @Descrb: 定时任务处理服务
 */
public class JobTaskService extends BaseService {
	public static Log log = LogFactory.getLog(JobTaskService.class);

	private JobTaskDao jobTaskDao;
	private SMSInterfaceService sMsService;
	private SelectedService selectedService;
	private UserService userService;
	private UserIntegralService userIntegralService;
	private FinanceDao financeDao;
	private AccountUsersDao   accountUsersDao;
	private BorrowManageDao  borrowManageDao;
	private InvestDao investDao;
	private BorrowDao  borrowDao;
	private RepayMentDao repayMentDao;
	private FrontMyPaymentDao frontpayDao;
	private FundRecordDao fundRecordDao;
	private UserDao userDao;
	private AssignmentDebtService assignmentDebtService;
	private GofullAwardDao gofullAwardDao;
	private PlatformCostService platformCostService;
	private GroupUserDao groupUserDao;
	private RechargeService rechargeService;
	
	

	public AccountUsersDao getAccountUsersDao() {
		return accountUsersDao;
	}

	public BorrowManageDao getBorrowManageDao() {
		return borrowManageDao;
	}

	public InvestDao getInvestDao() {
		return investDao;
	}

	public BorrowDao getBorrowDao() {
		return borrowDao;
	}

	public RepayMentDao getRepayMentDao() {
		return repayMentDao;
	}

	public FrontMyPaymentDao getFrontpayDao() {
		return frontpayDao;
	}

	public FundRecordDao getFundRecordDao() {
		return fundRecordDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public AssignmentDebtService getAssignmentDebtService() {
		return assignmentDebtService;
	}

	public void setRepayMentDao(RepayMentDao repayMentDao) {
		this.repayMentDao = repayMentDao;
	}

	public void setFundRecordDao(FundRecordDao fundRecordDao) {
		this.fundRecordDao = fundRecordDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setAssignmentDebtService(AssignmentDebtService assignmentDebtService) {
		this.assignmentDebtService = assignmentDebtService;
	}

	public void setFrontpayDao(FrontMyPaymentDao frontpayDao) {
		this.frontpayDao = frontpayDao;
	}

	public void setInvestDao(InvestDao investDao) {
		this.investDao = investDao;
	}
	
	public void setBorrowDao(BorrowDao borrowDao) {
		this.borrowDao = borrowDao;
	}

	public SelectedService getSelectedService() {
		return selectedService;
	}

	public void setAccountUsersDao(AccountUsersDao accountUsersDao) {
		this.accountUsersDao = accountUsersDao;
	}

	public void setBorrowManageDao(BorrowManageDao borrowManageDao) {
		this.borrowManageDao = borrowManageDao;
	}

	public void setSelectedService(SelectedService selectedService) {
		this.selectedService = selectedService;
	}

	public JobTaskDao getJobTaskDao() {
		return jobTaskDao;
	}

	public void setJobTaskDao(JobTaskDao jobTaskDao) {
		this.jobTaskDao = jobTaskDao;
	}

	public FinanceDao getFinanceDao() {
		return financeDao;
	}

	public void setFinanceDao(FinanceDao financeDao) {
		this.financeDao = financeDao;
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserIntegralService getUserIntegralService() {
		return userIntegralService;
	}

	public void setUserIntegralService(UserIntegralService userIntegralService) {
		this.userIntegralService = userIntegralService;
	}
	
	public GofullAwardDao getGofullAwardDao() {
		return gofullAwardDao;
	}
	public void setGofullAwardDao(GofullAwardDao gofullAwardDao) {
		this.gofullAwardDao = gofullAwardDao;
	}
	
	public GroupUserDao getGroupUserDao() {
		return groupUserDao;
	}
	public void setGroupUserDao(GroupUserDao groupUserDao) {
		this.groupUserDao = groupUserDao;
	}
	public PlatformCostService getPlatformCostService() {
		return platformCostService;
	}

	public void setPlatformCostService(PlatformCostService platformCostService) {
		this.platformCostService = platformCostService;
	}

	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	/**
	 * @MethodName: autoBid
	 * @Param: JobTaskService
	 * @Author: Mr.Zero
	 * @Date: 2018-7-31 10:32:43
	 * @Return:
	 * @Descb: 通联协议支付——交易查询
	 * @Throws:
	 */
	public void TransactionQuery() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();

		String reqsn="";//交易流水号(交易结果查询时，待查询的原支付交易流水号)
		Date rechargeTime;	//充值时间
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		AllinPaymentAction allinPaymentAction=new AllinPaymentAction();

		//设置安全提供者,注意，这一步尤为重要
		BouncyCastleProvider provider = new BouncyCastleProvider();
		XmlTools.initProvider(provider);

		List<Map<String, Object>> allinPayList = jobTaskDao.queryAllinPay(conn);  // 查询所有通联充值未成功

		//交易查询
		try {
			if(allinPayList != null){
				for (Map<String, Object> allinPayMap : allinPayList) {
					reqsn = allinPayMap.get("rechargeNumber").toString();	//交易查询请求流水号
					rechargeTime = dfs.parse(allinPayMap.get("rechargeTime").toString());	//充值时间
					long between=((new Date()).getTime()-rechargeTime.getTime())/1000;//除以1000是为了转换成秒
					long min=between/60;
					if(min<30){	//申请时间小于30分钟，执行交易查询
						if(reqsn != null){
							System.out.println("通联协议支付——交易查询请求流水号=======>>："+reqsn);
							try {
								allinPaymentAction.queryTradeNew(AllinpayConfig.alllin_gate_way, reqsn, false,"","");
								Thread.sleep(30000);	//间隔30秒
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}else{	//将超过30分钟充值未成功置为处理失败
						if(reqsn != null){
							System.out.println("通联协议支付——交易查询请求流水号=======>>："+reqsn);
							try {
								long result = rechargeService.updateRechargeDetailByRN(reqsn, 2, "");
								log.info("===================>>>处理结果，result：" + result);
								Thread.sleep(30000);	//间隔30秒
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			conn.rollback();
		} finally {
			conn.close();
		}
	}

	/**
	 * @MethodName: autoBid
	 * @Param: JobTaskService
	 * @Author: Mr.Zero
	 * @Date: 2018-7-31 10:32:43
	 * @Return:
	 * @Descb: 通联协议支付——将超过30分钟充值未成功置为处理失败
	 * @Throws:
	 */
	/*public void refundFail() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();

		String reqsn="";//交易流水号(交易结果查询时，待查询的原支付交易流水号)
		Date rechargeTime;	//充值时间
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		List<Map<String, Object>> allinPayList = jobTaskDao.queryAllinPay(conn);  // 查询所有通联充值未成功

		//交易查询
		try {
			if(allinPayList != null){
				for (Map<String, Object> allinPayMap : allinPayList) {
					reqsn = allinPayMap.get("rechargeNumber").toString();	//交易查询请求流水号
					rechargeTime = dfs.parse(allinPayMap.get("rechargeTime").toString());	//充值时间
					long between=((new Date()).getTime()-rechargeTime.getTime())/1000;//除以1000是为了转换成秒
					long min=between/60;
					if(min>30){	//申请时间大于30分钟，将处理结果置为失败
						if(reqsn != null){
							System.out.println("通联协议支付——交易查询请求流水号=======>>："+reqsn);
							try {
								long result = rechargeService.updateRechargeDetailByRN(reqsn, 2, "");
								log.info("===================>>>处理结果，result：" + result);
								Thread.sleep(30000);	//间隔30秒
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			conn.rollback();
		} finally {
			conn.close();
		}
	}*/
	
	/**
	 * @MethodName: autoBid
	 * @Param: JobTaskService
	 * @Author: zhaojun.xu
	 * @Date: 2014-2-18 14:32:43
	 * @Return:
	 * @Descb: 自动投标
	 * @Throws:
	 */
	public void autoBid() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();
		List<Map<String, Object>> biderList = jobTaskDao.queryAllBider(conn);  // 所有的符合条件的招标中的借款
		long returnId = -1;

		try {
			// 所有的符合条件招标中的借款
			for (Map<String, Object> biderMap : biderList) {
				int deadline = Convert.strToInt(biderMap.get("deadline").toString(), 0); // 借款期限
				int isDayThe = Convert.strToInt(biderMap.get("isDayThe").toString(), -1); // 是否天标
				double annualRate = Convert.strToDouble(biderMap.get("annualRate").toString(), 0); // 借款利率

				List<Map<String, Object>> userList = jobTaskDao.queryAutoBidUser(conn,isDayThe,deadline,annualRate);// 查询符合自动投标的用户
				// 所有符合条件的用户排队对借款进行自动投标
				for (Map<String, Object> userMap : userList) {
					long userId = Convert.strToLong(userMap.get("userId").toString(), -1); // 用户编号
					long borrowId = Convert.strToLong(biderMap.get("id").toString(), 0); // 子标编号
					Procedures.p_autobid(conn, ds, outParameterValues, userId,borrowId, -1, "");
					returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
					if(returnId < 0){
						conn.rollback();
					}
				}
			}
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * @Descb: 自动还款
	 * @Throws:
	 */
	public void autoRepayment() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		DataSet ds = new DataSet();
		List<Object> outParameterValues = new ArrayList<Object>();
		// 所有的符合条件的开启了自动还款的记录
		List<Map<String, Object>> repaymentList = jobTaskDao.queryAutoRepayment(conn);  
		long returnId = -1;
		int successCounts = 0;
		int failCounts = 0;
		
		try {
			if (null != repaymentList && repaymentList.size() > 0) {
				
				for (Map<String, Object> repayMap : repaymentList) {
					long repayId = Convert.strToLong(repayMap.get("repayId")
							.toString(), -1);
					long userId = Convert.strToLong(repayMap.get("userId")
							.toString(), -1);

					Procedures.p_borrow_repayment(conn, ds, outParameterValues,
							repayId, userId, "", "", new Date(),
							new BigDecimal(0), -1, "");
					returnId = Convert.strToLong(
							outParameterValues.get(0) + "", -1);

					if (returnId < 0) {
						conn.rollback();
						failCounts = failCounts + 1;
					} else {
						successCounts = successCounts + 1;
					}
				}
				conn.commit();
				
				//发送短信通知
				Map<String, String> smsMap = sMsService.getSMSById(1);
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				String smsCotent = nowTime + ",自动还款已执行！成功还款笔数：" + successCounts + " 失败笔数： " + failCounts;
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"),
						smsCotent, "18520867077" ,"");
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"),
						smsCotent, "18665866439" ,"");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			conn.rollback();
		} finally {
			conn.close();
		}
	}



	/**
	 * @MethodName: updateOverDueRepayment
	 * @Param: JobTaskService
	 * @Author: gang.lv
	 * @Date: 2013-4-11 下午02:42:50
	 * @Return:
	 * @Descb: 更新逾期的还款
	 * @Throws:
	 */
	public void updateOverDueRepayment() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		SimpleDateFormat sf = new SimpleDateFormat(UtilDate._dtShort);
		DecimalFormat df= new DecimalFormat("#0.00");
		List<Map<String,Object>> overDueRepaymentList = null;
		String date = sf.format(new Date());
		long borrowId = -1L;
		long id = -1;
		//应还本金
		double stillPrincipal = 0;
		//应还利息
		double stillInterest = 0;
		// 逾期罚息
		double lateFee = 0;
		//执行天数
		int executeDay = 0;
		//逾期天数
		int overdueDay = 0;
		//借款方式
		int borrowWay = 0;
		//执行时间
		String executeTime ="";
		//-- 7 - 9
		//查询借款信息得到借款时插入的平台收费标准
		Map<String,String> map = new HashMap<String, String>();
		String feelog = "";
		Map<String,Double> feeMap = new HashMap<String, Double>();
		//得到收费标准的说明信息
		String feestate = "";
		Map<String,String> feestateMap = new HashMap<String, String>();
		//--end
		double overdueFeeRate = 0;
		try {
			overDueRepaymentList = jobTaskDao.queryOverDueRepayment(conn,date);
			for(Map<String,Object> overDueMap:overDueRepaymentList){
				id = Convert.strToLong(overDueMap.get("id")+"", -1);
				borrowId = Convert.strToLong(overDueMap.get("borrowId")+"", 0);
				stillPrincipal = Convert.strToDouble(overDueMap.get("stillPrincipal")+"", 0);
				stillInterest = Convert.strToDouble(overDueMap.get("stillInterest")+"", 0);
				executeTime = overDueMap.get("executeTime")+"";
				
				overdueDay = Convert.strToInt(overDueMap.get("overdueDay")+"", 0);
				map = borrowManageDao.queryBorrowInfo(conn, borrowId);
				if(map!=null){
					//得到罚息利率
					overdueFeeRate =Convert.strToDouble(map.get("overdueFee"),0);
					borrowWay = Convert.strToInt(map.get("borrowWay"), 0);
				}else{
					overdueFeeRate = 0;
				}
				//不符合条件的情况，将逾期天数重置为0
				if(overdueDay < 0){
					overdueDay = 0;
				}
				if (borrowWay ==6) {//流转标不计算罚息
					overdueDay = 0;
				}
				// 计算罚息=本息
				lateFee = (stillPrincipal + stillInterest) * overdueDay * (overdueFeeRate / 100);
				lateFee = Double.valueOf(df.format(lateFee));
				// 更新逾期还款
				if(overdueDay >0){
					jobTaskDao.updateOverDueRepayment(conn, id, lateFee,overdueDay,date);
				}
				// 回收对象
				overDueMap = null;
				map = null;
				feeMap = null;
				feestateMap = null;
				//提交任务
				conn.commit();
			}
		}catch(Exception e){
			e.printStackTrace();
			log.equals(e);
			conn.rollback();
		} finally {
			conn.close();
			conn = null;
		    sf = null;
			df= null;
			overDueRepaymentList = null;
			System.gc();
		}
	}


	/**   
	 * @MethodName: updateOverDueInvestRepayment  
	 * @Param: JobTaskService  
	 * @Author: gang.lv
	 * @Date: 2013-6-2 下午10:25:20
	 * @Return:    
	 * @Descb: 更新逾期投资还款记录
	 * @Throws:
	*/
	public void updateOverDueInvestRepayment() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		SimpleDateFormat sf = new SimpleDateFormat(UtilDate._dtShort);
		DecimalFormat df= new DecimalFormat("#0.00");
		List<Map<String,Object>> overDueRepaymentList = null;
		String date = sf.format(UtilDate.getYesterDay());
		long id = -1;
		//应还本金
		double stillPrincipal = 0;
		//应还利息
		double stillInterest = 0;
		//逾期罚息
		double lateFee = 0;
		long repayId = 0;
		int lateDay= 0;
		int isLate= 0 ;
		int borrowWay= 0;
		//-- 7 - 9
		//查询借款信息得到借款时插入的平台收费标准
		Map<String,String> map = null;
		String feelog = "";
		Map<String,Double> feeMap = null;
		//得到收费标准的说明信息
		String feestate = "";
		Map<String,String> feestateMap = null;
		//--end
		double overdueFeeRate =0;
		try {
			overDueRepaymentList = jobTaskDao.queryOverDueInvestRepayment(conn,date);
			for(Map<String,Object> overDueMap:overDueRepaymentList){
				long borrowId = Convert.strToLong(overDueMap.get("borrowId")+"", 0);
				map = borrowManageDao.queryBorrowInfo(conn, borrowId);
			 	//得到罚息利率
				overdueFeeRate = Convert.strToDouble( map.get("overdueFee"),0);
					
			    //计算罚息
				id = Convert.strToLong(overDueMap.get("id")+"", -1);
				repayId = Convert.strToLong(overDueMap.get("repayId")+"", -1);
				lateDay = Convert.strToInt(overDueMap.get("lateDay")+"", 0);
				isLate = Convert.strToInt(overDueMap.get("isLate")+"", 1);
				stillPrincipal = Convert.strToDouble(overDueMap.get("recivedPrincipal")+"", 0);
				stillInterest = Convert.strToDouble(overDueMap.get("recivedInterest")+"", 0);
				lateFee = (stillPrincipal+stillInterest) * (overdueFeeRate / 100) * lateDay;
			    lateFee = Double.valueOf(df.format(lateFee));
			    borrowWay = Convert.strToInt(overDueMap.get("borrowWay")+"", 0);
			    //更新逾期还款
			    // 6 为流转标 不处理
			    if ( borrowWay !=6) { 
			    	jobTaskDao.updateOverDueInvestRepayment(conn,id,repayId,lateFee,lateDay,isLate);
				}
			    //回收对象
			    overDueMap = null;
				map = null;
				feeMap = null;
				feestateMap = null;
			}
			conn.commit();
		}catch(Exception e){
			e.printStackTrace();
			log.equals(e);
			conn.rollback();
		} finally {
			conn.close();
			conn = null;
		    sf = null;
			df= null;
			overDueRepaymentList = null;
			System.gc();
		}
	}
	
	
	/**
	 * 发送短信 模板
	 * @throws SQLException
	 */
	public void sendtoTemple() throws SQLException{
		Connection conn = MySQL.getConnection();
		Map<String,String>  noticeMap = new HashMap<String, String>();
		List<Map<String,Object>> tmplList = new ArrayList<Map<String,Object>>();
		PageBean<Map<String,Object>>  pagebean = new PageBean<Map<String,Object>>();
		long investor = -1;
		String title = "";
		int id = 0;
		try {
			pagebean.setPageSize(150);
			jobTaskDao.queryTmpleAll(conn,pagebean);
			tmplList = pagebean.getPage();
			if (tmplList!=null) {
				for (Map<String, Object> map : pagebean.getPage()) {
					investor = Convert.strToLong(map.get("user_id")+"",-1L);
					title = Convert.strToStr(map.get("sendtitle")+"", "");
					id = Convert.strToInt(map.get("id")+"", -1);
					noticeMap.put("email", Convert.strToStr(map.get("email_info")+"",""));
					noticeMap.put("mail", Convert.strToStr(map.get("mail_info")+"",""));
					noticeMap.put("note", Convert.strToStr(map.get("sms_info")+"",""));
					noticeMap.put("operate_id", Convert.strToStr(map.get("operate_id")+"",""));
					selectedService.sendNoticeMSG(conn, investor,
							title, noticeMap, Convert.strToStr(map.get("s_nid")+"",""));
					
				 Functions.f_send_temple(conn,id);
					map = null;
				}
			}
			conn.commit();
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		}finally{
			conn.close();
			noticeMap = null;
			pagebean = null;
			tmplList = null;
			System.gc();
		}
	}

	public void autoBidProTask() throws Exception {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_autobid_task(conn, ds, outParameterValues, IConstants.WEB_URL, -1, "");
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
	}
	

	/**
	 * 定时发布标的
	 * @throws SQLException
	 */
	public void publistBorrow() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateBorrow(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	
	/**
	 * 每日清算余额宝利息
	 * @param conn
	 * @throws SQLException
	 */
	public void yebDailyLiquidation() throws SQLException{
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_yeb_daily_liquidation(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			
			//发送短信通知
			Map<String, String> smsMap = sMsService.getSMSById(1);
			if(returnId < 0){
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",余额宝每日清算脚本执行失败！", "18520867077" ,"");
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",余额宝每日清算脚本执行失败！", "18665866439" ,"");
			}else{
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",余额宝每日清算脚本执行成功！", "18520867077" ,"");
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",余额宝每日清算脚本执行成功！", "18665866439" ,"");
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 每日清算共富奖励
	 * @param conn
	 * @throws SQLException
	 */
	public void gofullAwardDailyLiquidation() throws SQLException{
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_gofull_award_daily_liquidation(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			
			//发送短信通知
			Map<String, String> smsMap = sMsService.getSMSById(1);
			if(returnId < 0){
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",共富奖励每日清算脚本执行失败！", "18520867077" ,"");
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",共富奖励每日清算脚本执行失败！", "18665866439" ,"");
			}else{
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",共富奖励每日清算脚本执行成功！", "18520867077" ,"");
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",共富奖励每日清算脚本执行成功！", "18665866439" ,"");
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 撤销所有债权转让
	 * @throws SQLException
	 */
	public void updateAssignment() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateAssignment(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	/**
	 * 发布借款
	 * @param conn
	 * @throws SQLException
	 */
	public void publishBorrow() throws Exception {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_create_borrow_product(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 自有资金购买余额宝投资赎回
	 * @param conn
	 * @throws SQLException
	 */
	public void yebTzshByWebsite() throws SQLException {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.p_yeb_tzsh_buy_website(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			
			//发送短信通知
			Map<String, String> smsMap = sMsService.getSMSById(1);
			if(returnId > 0){
				String nowTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), nowTime + ",自有资金购买余额宝投资赎回成功！", "18665866439" ,"");
			}
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 每日在库清算
	 * @param conn
	 * @throws SQLException
	 */
	public void mrzk() throws SQLException {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.pr_rb_mrzk(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 每日运行简报清算
	 * @param conn
	 * @throws SQLException
	 */
	public void mryxjb() throws SQLException {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.pr_rb_mryxjb(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 每日客户费用清算
	 * @param conn
	 * @throws SQLException
	 */
	public void mrkhfy() throws SQLException {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.pr_rb_khfy(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}
	
	/**
	 * 每月在库清算
	 * @param conn
	 * @throws SQLException
	 */
	public void myzk() throws SQLException,DataException {
		Connection conn = MySQL.getConnection();
		try {
			DataSet ds = new DataSet();
			List<Object> outParameterValues = new ArrayList<Object>();
			Procedures.pr_yb_myzk(conn, ds, outParameterValues, -1, "");
			long returnId = Convert.strToLong(outParameterValues.get(0) + "", -1);
			conn.commit();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			conn.rollback();
		} finally {
			conn.close();
		}
	}

	public SMSInterfaceService getsMsService() {
		return sMsService;
	}

	public void setsMsService(SMSInterfaceService sMsService) {
		this.sMsService = sMsService;
	}
	
	public void updateOverdueElite() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateOverdueElite(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	public void updateOverdueEliteInterest() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateOverdueEliteInterest(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	public void updateEliteInterest() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateEliteInterest(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	public void updateOverdueVoucher() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateOverdueVoucher(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	public void updateOverdueVoucherCode() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateOverdueVoucherCode(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	public void updateOverdueWechatAutoLogin() throws SQLException{
		Connection conn =MySQL.getConnection();
		try {
			jobTaskDao.updateOverdueWechatAutoLogin(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
			log.error(e);
		}finally{
			conn.close();
		}
		
	}
	
	/**
	 * @MethodName: sendWarningMsg
	 * @Param: JobTaskService
	 * @Author: wujc
	 * @Date: 2015-05-28
	 * @Return:
	 * @Descb: 预警通知
	 * @Throws:
	 */
	public void sendWarningMsg() throws SQLException, DataException {
		Connection conn = Database.getConnection();
		List<Map<String, Object>> msgList = jobTaskDao.queryAllWarningMsg(conn);
		try {
			Map<String, String> smsMap = sMsService.getSMSById(1);
			for (Map<String, Object> msgMap : msgList) {
				long id = Convert.strToLong(msgMap.get("id")+"", -1);
				String email = Convert.strToStr(msgMap.get("userEmail")+"","");
				String telPhone = Convert.strToStr(msgMap.get("userTelPhone")+"","");
				String msgTitle = Convert.strToStr(msgMap.get("msgTitle")+"","");
				String msgCotent = Convert.strToStr(msgMap.get("msgCotent")+"","");
				if(id > 0){
					//发送短信通知
					String smsResult = SMSUtil.sendSMS(smsMap.get("Account"), smsMap.get("Password"), msgCotent, telPhone ,"");
					
					//发送邮件通知
					
					//更新发送状态
					if("Sucess".equals(smsResult)){
						jobTaskDao.updateWarningMsgSendStatus(conn, id);
					}
				}
			}
			conn.commit();		
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			conn.rollback();
		} finally {
			conn.close();
		}
	}
}
